const createError = require('http-errors')
const express = require('express')
const path = require('path')
const cookieParser = require('cookie-parser')
const logger = require('morgan')
const ws = require('ws')

const indexRouter = require('./routes/index')
const usersRouter = require('./routes/users')
const sourcesRouter = require('./routes/sources')
const novelsRouter = require('./routes/novels')

const { db } = require('novel-parser')
const { handler } = require('./services/websocket')

db.setBasePath(__dirname)

const app = express()

// view engine setup
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'ejs')

app.use(logger('dev'))
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
app.use(cookieParser())
app.use(express.static(path.join(__dirname, 'public')))

app.use('/', indexRouter)
app.use('/users', usersRouter)
app.use('/', sourcesRouter)
app.use('/', novelsRouter)

const wsServer = new ws.Server({ noServer: true })
wsServer.on('connection', socket => {
  socket.on('message', message => handler(socket, JSON.parse(message)))
  socket.send(JSON.stringify({ code: 200, message: 'connected' }))
})

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404))
})

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  console.error(err)
  res.json({ code: err.status || 500, message: err.message, error: err })
})

module.exports = { app, wsServer }
